package io.renren.modules.generator.service.impl;

import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import io.renren.modules.generator.dto.FireData;
import io.renren.modules.generator.dto.JsonRootBean;
import io.renren.modules.job.service.HttpClientService;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.generator.dao.FireForecastDataDao;
import io.renren.modules.generator.entity.FireForecastDataEntity;
import io.renren.modules.generator.service.FireForecastDataService;


@Service("fireForecastDataService")
public class FireForecastDataServiceImpl extends ServiceImpl<FireForecastDataDao, FireForecastDataEntity> implements FireForecastDataService {

    @Autowired
    FireForecastDataService fireForecastDataService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FireForecastDataEntity> page = this.page(
                new Query<FireForecastDataEntity>().getPage(params),
                new QueryWrapper<FireForecastDataEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void parseCSV(String path) throws FileNotFoundException {
        File file = new File(path);
        if (!file.exists() || file.isDirectory()) {
            return;
        }
        InputStreamReader inputStream = new InputStreamReader(new FileInputStream(path), CharsetUtil.CHARSET_GBK);
        // 设置解析策略，csv的头和POJO属性的名称对应，也可以使用@CsvBindByName注解来指定名称
        HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy();
        strategy.setType(FireData.class);

        CsvToBean csvToBean = new CsvToBeanBuilder(inputStream)
                .withMappingStrategy(strategy)
                .withSkipLines(1)
                .build();
        List<FireData> carCsvDTOList = csvToBean.parse();
        List<FireForecastDataEntity> collect = carCsvDTOList.stream()
                .filter(
                        (item2)->{
                            //在调用api之间先过滤一下应该就贼快了
                            return item2.getLng() < 117.27D && item2.getLat() >33.01D && item2.getLat() <40.98D;
                        }
                )
                .map(
                (item) -> {
                    FireForecastDataEntity entity = new FireForecastDataEntity();
                    BeanUtils.copyProperties(item, entity);
                    entity.setFireTime(new Date());
                    List<NameValuePair> list = new ArrayList<>();

                    list.add(new BasicNameValuePair("type", "geocode"));
                    list.add(new BasicNameValuePair("tk", "9853468a2871b2835892b78b2b6015bc"));
                    list.add(new BasicNameValuePair("postStr", "{'lon':" + item.getLng() + ",'lat':" + item.getLat() + ",'ver':1}"));
                    try {
                        JSONObject json = (JSONObject) HttpClientService.sendGet("http://api.tianditu.gov.cn/geocoder", list);

                        JsonRootBean jsonRootBean = JSON.parseObject(json.toString(), JsonRootBean.class);
                        entity.setAddress(jsonRootBean.getResult().getAddressComponent().getAddress());
                        entity.setAddressCode(jsonRootBean.getResult().getAddressComponent().getCounty_code());
                        if (jsonRootBean.getResult().getAddressComponent().getCounty_code() != null){
                            boolean flag = jsonRootBean.getResult().getAddressComponent().getCounty_code().equals("");
                            if ( flag != true){
//                            System.out.println(jsonRootBean.getResult().getAddressComponent().getCounty_code().substring(0,5));
//                            System.out.println(jsonRootBean.getResult().getAddressComponent().getCounty_code().substring(3));
                                if (jsonRootBean.getResult().getAddressComponent().getCounty_code().substring(0,5).equals("15614")){
                                    entity.setAddressCode(jsonRootBean.getResult().getAddressComponent().getCounty_code().substring(3));
                                    System.out.println("存储");

                                    fireForecastDataService.save(entity);
                                }
                            }
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return entity;
                }
        ).collect(Collectors.toList());

    }

}